package com.fh.service.impl;

import com.fh.entity.po.User;
import com.fh.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class UserServiceImpl implements com.fh.service.UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public Integer userIsExist(String name) {
        User user = userMapper.getUserByName(name);
        if (user==null){
            return 0;
        }
        else {
            return 1;
        }
    }

    @Override
    public void register(User user) {
        User userByName = userMapper.getUserByName(user.getName());
        if (userByName!=null){
            throw new RuntimeException("用户名已存在");
        }

        String str = "^([a-zA-Z0-9_\\-.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern compile = Pattern.compile(str);
        Matcher matcher = compile.matcher(user.getEmail());
        if (matcher.matches()==false){
            throw new RuntimeException("请输入正确的邮箱");
        }

        String password = com.fh.utils.MD5Util.encoder(com.fh.utils.MD5Util.encoder(user.getPassword())+user.getName());
        user.setPassword(password);
        user.setCreateDate(new Date());

        userMapper.addUser(user);

        Long count = userMapper.queryUserCount();

        com.fh.thread.EmailThread emailThread = new com.fh.thread.EmailThread(user.getEmail(),"不知名系统",count+"");
        emailThread.start();

    }

    @Override
    public Integer updatePassword(User user) {
        User userByName = userMapper.getUserByName(user.getName());
        if (userByName==null){
            throw new RuntimeException("处理异常，参数异常");
        }
        userByName.setPassword(com.fh.utils.MD5Util.encoder(com.fh.utils.MD5Util.encoder(user.getPassword())+user.getName()));
        userMapper.updatePassword(userByName);
        return 0;
    }

    @Override
    public com.fh.entity.vo.TableData<com.fh.entity.vo.UserShow> queryUserPageData(com.fh.entity.vo.UserParam param) {
        com.fh.entity.vo.TableData<com.fh.entity.vo.UserShow> rs = new com.fh.entity.vo.TableData<>();
        List<com.fh.entity.vo.UserShow> list = userMapper.queryUserPageData(param);
        Long count = userMapper.queryCount(param);
        rs.setMsg("success");
        rs.setCount(count);
        rs.setData(list);
        return rs;
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.updateUserInfo(user);
    }


}
